package com.crm.manager.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.common.core.page.TableDataInfo;
import com.crm.manager.domain.Clue;
import com.crm.manager.domain.ClueRecord;
import com.crm.manager.domain.dto.ClueRecordDto;
import com.crm.manager.domain.vo.ClueRecordVo;
import com.crm.manager.mapper.ClueRecordMapper;
import com.crm.manager.service.ClueRecordService;
import com.crm.manager.service.ClueService;
import com.crm.manager.utils.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClueRecordServiceImpl extends ServiceImpl<ClueRecordMapper, ClueRecord> implements ClueRecordService {

    @Autowired
    private ClueRecordMapper clueRecordMapper;
    @Autowired
    private ClueService clueService;

    // 添加跟进
    @Override
    @Transactional
    public void addClueRecord(ClueRecordDto clueRecordDto) {
        // 根据clueId查询线索信息
        Clue clue = clueService.getOne(Wrappers.<Clue>lambdaQuery().eq(Clue::getId, clueRecordDto.getClueId()));
        // 通过clueRecordDto将clue信息补上，并保存
        BeanUtils.copyProperties(clueRecordDto,clue);
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(Clue.CLUE_STATUS_ING);
        clueService.update(clue,Wrappers.<Clue>lambdaUpdate().eq(Clue::getId, clueRecordDto.getClueId()));
        // 添加到clue_record表中
        ClueRecord clueRecord = new ClueRecord();
        BeanUtils.copyProperties(clueRecordDto,clueRecord);
        clueRecord.setCreateBy(BaseContext.getUserName());
        clueRecord.setCreateTime(LocalDateTime.now());
        this.save(clueRecord);
    }

    // 根据clueId查询线索跟进记录
    @Override
    public TableDataInfo selectByClueId(Long clueId) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        List<ClueRecordVo> list = clueRecordMapper.selectByClueId(clueId);
        tableDataInfo.setRows(list);
        tableDataInfo.setTotal(list.size());
        tableDataInfo.setCode(200);
        return tableDataInfo;
    }
}
